-- Start everything moving
-- Runtime:addEventListener( "enterFrame", move );
--module(...,package.seeall)
local physics = require( "physics" )
physics.start()
 
local storyboard = require( "storyboard" )
local scene = storyboard.newScene()
local baseline = 2*display.contentHeight/3
local mapGame = require("mapGame");

local gameConstant = require("GameConstant")
local sprite = require("sprite");
local loader = require ("loader");

local x=0;
local y=0;
local options =
{
	frames = require("player").frames,
}


local animationData ={
 { name="runOption", start=1, count=14, time= 300},
 { name="rollOption", start=15, count=28, time= 1000},
 { name="jumpOption", start=43, count=1, time= 300},
 { name = "dieOption",start = 44, count = 1, time = 100}
 
}

     
-- The new sprite API
for i=0,#mapGame.tree,1 do 
    display.remove( mapGame.tree[i] )
    --mapGame.tree[i]= nil
end
mapGame.tree={}
local runPlayer = graphics.newImageSheet( "images/gElem.png", options )
local playerInstance = display.newSprite( runPlayer, animationData)

playerInstance:setReferencePoint(display.TopLeftReferencePoint)
playerInstance.x = display.contentWidth/4 + 10
playerInstance.y = baseline - gameConstant.heightGrass; 
playerInstance:setSequence("runOption")

playerInstance:play();

physics.addBody( playerInstance, { density = 3.0, friction = 0.5, bounce = 0.2 } )
playerInstance.isFixedRotation = true
--Set the rectangle's body active state
--playerInstance.isBodyActive = false;


local function move(event ) end
local count = 10;
for i=1,10,1 do
   name="box"..i..".png" 
   mapGame.obstacle[i]=display.newImage( "images/obstack.png" )
   mapGame.obstacle[i]:setReferencePoint( display.TopLeftReferencePoint )
   x,y=loader.getdata1(name)
    if i == 1 then 
        mapGame.obstacle[i].x = x + 600
    else 
        mapGame.obstacle[i].x = mapGame.obstacle[i-1].x + x;
    end
    mapGame.obstacle[i].y = baseline - gameConstant.heightGrass - y;
    mapGame.obstacle[i].width = gameConstant.widthObstack;
    mapGame.obstacle[i].height = gameConstant.heightObstack;
    mapGame.obstacle[i].tag = "obstack";
    physics.addBody( mapGame.obstacle[i], "static", { density = 1.0, friction = 0, bounce = 0 } )
    --print(mapGame.obstacle[i].y);
end

local tPrevious = system.getTimer()
local function move(event)
    local tDelta = event.time - tPrevious
    tPrevious = event.time
    local xOffset = (gameConstant.speed * tDelta )
    for i=1,10,1 do
        mapGame.obstacle[i].x = mapGame.obstacle[i].x - xOffset;
        
        if (mapGame.obstacle[i].x + 18) < 0 then
            name="box"..(count+i)..".png"
            x,y=loader.getdata1(name);
            if i == 1 then 
                mapGame.obstacle[i].x  = mapGame.obstacle[10].x + x
            else 
                mapGame.obstacle[i].x = mapGame.obstacle[i-1].x + x 
            end
            mapGame.obstacle[i].y = baseline -gameConstant.heightGrass - y;
            --print (mapGame.obstacle[i].x)
            if i == 10 then  count = count + 10; end 
            if count  == 40 then count = 0; end
        
        end  
        --mapGame.obstacle[i]:translate( 0, 0 )
    end    
end
    
    
------------------------------------------------------
-- cat collision Event
------------------------------------------------------
local function playerCollision(seft,event)
        local object = event.other;
            if event.phase == "began" then	
                    if object.tag == "obstack" then
                       print("Roll:"..playerInstance.height);
                       print("Y:"..playerInstance.y);
                       print("Obstack.Y:"..object.y);
                       
                       gameConstant.speed = 0;
                       gameConstant.speedBuilding = 0;
                        --[[playerInstance:setSequence( "dieOption" )
                        
                        playerInstance:play();
                        --local menu = storyboard.loadScene( "menu" )
                        
                        gameConstant.speed = 0;
                        gameConstant.speedBuilding = 0;
                        physics.setGravity( 0, playerInstance.y/2 )
                        playerInstance:applyForce(5000, 10000, playerInstance.x, playerInstance.y )
                        playerInstance.angularVelocity = 360
                        timer.performWithDelay( 1,
                        function( ) 
                            --playerInstance:stop( )
                            for i = 1,#mapGame.obstacle, 1 do 
                                physics.removeBody(mapGame.obstacle[i])
                            end
                            physics.removeBody(mapGame.grass )                             
                        end) --]]   
                    elseif object.tag=="way" then
                       playerInstance:setSequence("runOption" )
                       print("Run:"..playerInstance.height);
                       playerInstance:play();
                       print("run again");
                   end
--               elseif event.phase=="ended" and object.tag=="way" then
--                    playerInstance:setSequence("runOption" )
--                    playerInstance:play();
--                    print("run again");          
               
        end
        if event.other.isBurger and event.other.isVisible == true then
               
        end
        if event.other.isMultiplier and event.other.isVisible == true then
            
        end
    end
 playerInstance.collision = playerCollision;
 playerInstance:addEventListener("collision", playerInstance);
 
local startTime
local onTouch = function(event)
    if event.phase == "began"   then -- event hold a variable that states touch phases ( begin, moved, ended )
        startTime=event.time
        print ("Sequence:"..playerInstance.sequence)
        if event.x <= display.contentWidth/2 and 
            playerInstance.sequence=="runOption"   
        then
            playerInstance:setSequence("rollOption" );
            playerInstance:play();
            --status=true
            timer.performWithDelay( 1000, function( )
                --print ("Run")
                playerInstance:setSequence("runOption" )
                playerInstance:play();
                
            end)
        end 
            
    elseif event.phase == "ended" and event.x > display.contentWidth/2 and 
            playerInstance.sequence=="runOption" then
            --print ( "Jump" );
            --print (playerInstance.y);
            playerInstance:setSequence("jumpOption" )
            playerInstance:play();
            if (playerInstance.y > baseline - 120) then  
            --print ( "Jump" );   
            force=(event.time-startTime)*5
            if(force>1200) then force=1200 end
            --print("jump event:"..force)
            playerInstance:applyForce( 0, -force, playerInstance.x, playerInstance.y )
            timer.performWithDelay( 1000, 
            function( )
                --print ("Run")
                playerInstance:setSequence("runOption" )
                playerInstance:play();
                
            end)
            end 
        end

end
---------------------------------------------------------------------------------
-- BEGINNING OF YOUR IMPLEMENTATION
---------------------------------------------------------------------------------

-- Called when the scene's view does not exist:
function scene:createScene( event )
        local group = self.view
        local background = display.newImageRect( "images/menu/background.png", display.contentWidth, display.contentHeight )
        --local background = display.newImage( "images/menu/backgroundCity.png", true )
	background:setReferencePoint( display.TopLeftReferencePoint )
	background.x, background.y = 0, 0
        group:insert(background)
        -----------------------------------------------------------------------------

        --      CREATE display objects and add them to 'group' here.
        --      Example use-case: Restore 'group' from previously saved state.

        -----------------------------------------------------------------------------

end



-- Called BEFORE scene has moved onscreen:
function scene:willEnterScene( event )
        
        -----------------------------------------------------------------------------

end


-- Called immediately after scene has moved onscreen:
function scene:enterScene( event )
        local group = self.view
   
       -- group:insert( player )
        -----------------------------------------------------------------------------

        --      This event requires build 2012.782 or later.
        -----------------------------------------------------------------------------

        --      INSERT code here (e.g. start timers, load audio, start listeners, etc.)

        -----------------------------------------------------------------------------

end


-- Called when scene is about to move offscreen:
function scene:exitScene( event )
        local group = self.view

        -----------------------------------------------------------------------------

        --      INSERT code here (e.g. stop timers, remove listeners, unload sounds, etc.)

        -----------------------------------------------------------------------------

end


-- Called AFTER scene has finished moving offscreen:
function scene:didExitScene( event )
        local group = self.view

        -----------------------------------------------------------------------------

        --      This event requires build 2012.782 or later.

        -----------------------------------------------------------------------------

end


-- Called prior to the removal of scene's "view" (display group)
function scene:destroyScene( event )
        local group = self.view

        -----------------------------------------------------------------------------

        --      INSERT code here (e.g. remove listeners, widgets, save state, etc.)

        -----------------------------------------------------------------------------

end


-- Called if/when overlay scene is displayed via storyboard.showOverlay()
function scene:overlayBegan( event )
        local group = self.view
        local overlay_name = event.sceneName  -- name of the overlay scene

        -----------------------------------------------------------------------------

        --      This event requires build 2012.797 or later.

        -----------------------------------------------------------------------------

end


-- Called if/when overlay scene is hidden/removed via storyboard.hideOverlay()
function scene:overlayEnded( event )
        local group = self.view
        local overlay_name = event.sceneName  -- name of the overlay scene

        -----------------------------------------------------------------------------

        --      This event requires build 2012.797 or later.

        -----------------------------------------------------------------------------

end



---------------------------------------------------------------------------------
-- END OF YOUR IMPLEMENTATION
---------------------------------------------------------------------------------

-- "createScene" event is dispatched if scene's view does not exist
scene:addEventListener( "createScene", scene )

-- "willEnterScene" event is dispatched before scene transition begins
scene:addEventListener( "willEnterScene", scene )

-- "enterScene" event is dispatched whenever scene transition has finished
scene:addEventListener( "enterScene", scene )

-- "exitScene" event is dispatched before next scene's transition begins
scene:addEventListener( "exitScene", scene )

-- "didExitScene" event is dispatched after scene has finished transitioning out
scene:addEventListener( "didExitScene", scene )

-- "destroyScene" event is dispatched before view is unloaded, which can be
-- automatically unloaded in low memory situations, or explicitly via a call to
-- storyboard.purgeScene() or storyboard.removeScene().
scene:addEventListener( "destroyScene", scene )

-- "overlayBegan" event is dispatched when an overlay scene is shown
scene:addEventListener( "overlayBegan", scene )

-- "overlayEnded" event is dispatched when an overlay scene is hidden/removed
scene:addEventListener( "overlayEnded", scene )

---------------------------------------------------------------------------------
Runtime:addEventListener( "enterFrame", move );
Runtime:addEventListener("touch",onTouch);
return scene
